/**********************************************************
 * TranslationSystemServiceDelegator.java.java
 *
 * Created by punam
 * Last modified Date: Sep 9, 2008 8:28:45 AM by punam
 * Revision: <svn revision #>
 * Version : 0.1
 * Copyright (c) 2008 - 2009 cyberThink Infotech Pvt. Ltd., All rights reserved.
 **********************************************************/

package com.printeverywhere.delegator;

import static com.printeverywhere.util.AdminConstants.*;
import static com.printeverywhere.util.AttributeConstants.CLOSING_SESSION;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.printeverywhere.dto.GeneralCategories;
import com.printeverywhere.dto.Languages;
import com.printeverywhere.dto.User;
import com.printeverywhere.util.AdminConstants;
import com.printeverywhere.util.HibernateUtil;
import com.printeverywhere.util.SearchCriteria;

/**
 * TranslationSystemServiceDelegator Class performs the database operations for
 * the Languages. It allows user to add, Edit the language, set the default
 * language. Set the preference for the language(active/deactive).
 *
 * @author punam
 */
public class TranslationSystemServiceDelegator {

	/** The Constant UPDATE_QUERY. */
	private static final String UPDATE_QUERY = "UPDATE Languages SET languageCode = ?, languageName = ?, active = ?, default_ = ? WHERE languageCode = ?";

	/** The logger. */
	private static Logger logger = Logger
			.getLogger(LocationCategoriesServiceDelegator.class);

	/**
	 * Returns all the records from languages table without checking any
	 * predefined criteria, It simply list all the rows from database table.
	 *
	 * @return the list
	 *
	 * @throws HibernateException
	 *             the hibernate exception
	 */
	public static List<Languages> getList() throws HibernateException {
		logger.info(GET_LIST_WITHOUT_SEARCH_CRITERIA);
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		try {
			List<Languages> list = session.createCriteria(Languages.class)
					.list();
			transaction.commit();
			return list;
		} catch (HibernateException e) {
			logger.error(ERROR_GET_LIST_WITHOUT_SEARCH_CRITERIA
					+ e.getMessage());
			if (transaction != null) {
				transaction.rollback();
			}
			e.printStackTrace();
			throw e;
		} finally {
			logger.info(SESSION_CLOSED);
			session.close();
		}
	}

	public static List<Languages> getList(SearchCriteria searchCriteria)
			throws HibernateException {
		if (logger.isInfoEnabled()) {
			logger.info("Getting list for Languages with search criteria".intern());
		}
		Session session = HibernateUtil.getSession();
		Criteria criteria = session.createCriteria(Languages.class);
		String orderBY = searchCriteria.getOrderBy();
		if (orderBY != null) {
			if (searchCriteria.isAsc()) {
				criteria.addOrder(Order.asc(orderBY));
			} else {
				criteria.addOrder(Order.desc(orderBY));
			}
		}
		Set<String> keys = searchCriteria.getAttributeNames();
		Iterator<String> it = keys.iterator();
		String key = null;
		Object value = null;
		while (it.hasNext()) {
			key = it.next();
			value = searchCriteria.getAttribute(key);

			criteria.add(Restrictions.eq(key, value));
		}
		Transaction transaction = session.beginTransaction();
		List<Languages> list;
		try {
			list = criteria.list();
			transaction.commit();
		} catch (HibernateException e) {
			logger.error("Got exception when getting list for Languages with search criteria".intern());
			throw e;
		} finally {
			if (logger.isInfoEnabled()) {
				logger.info(CLOSING_SESSION);
			}
			session.flush();
			HibernateUtil.closeSession();
		}
		return list;
	}

	/**
	 * Adds the languages object to Languages table.
	 *
	 * @param languages
	 *            the languages
	 *
	 * @return the string
	 *
	 * @throws HibernateException
	 *             the hibernate exception
	 */
	public static String add(Languages languages) throws HibernateException {
		logger.info(CALLED_ADD_METHOD);
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		try {
			session.save(languages);
			transaction.commit();
			logger.info(RECORD_ADDED);
		} catch (HibernateException e) {
			logger.info(ERROR_IN_ADDING_THE_RECORD);
			transaction.rollback();
			throw e;
		} finally {
			logger.info(SESSION_CLOSED);
			session.close();
		}
		return AdminConstants.RECORD_ADDED;
	}

	/**
	 * Gets the Languages object where languageCode value matches with given
	 * languageCode.
	 *
	 * @param languageCode
	 *            the language Code
	 *
	 * @return the languages
	 *
	 * @throws HibernateException
	 *             the hibernate exception
	 */
	public static Languages get(String languageCode) throws HibernateException {
		logger.info("Called get method".intern());
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		Languages languages = null;
		try {
			languages = (Languages) session.get(Languages.class, languageCode);
			transaction.commit();
		} catch (HibernateException e) {
			logger.info("Error in getting the object for given languageCode "
					.intern()
					+ e.getMessage());
			transaction.rollback();
			throw e;
		} finally {
			logger.info(SESSION_CLOSED);
			session.close();
		}
		return languages;
	}

	/**
	 * Update the given modified languages object to the old object.
	 *
	 * @param translationSystem
	 *            the translation system
	 *
	 * @return the string
	 *
	 * @throws HibernateException
	 *             the hibernate exception
	 */
	public static String update(Languages translationSystem)
			throws HibernateException {
		logger.info(CALLED_UPDATE_METHOD);
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		try {
			Query query = session.createQuery(UPDATE_QUERY);
			query.setString(0, translationSystem.getLanguageCode());
			query.setString(1, translationSystem.getLanguageName());
			query.setBoolean(2, translationSystem.getActive());
			query.setBoolean(3, translationSystem.getDefault_());
			query.setString(4, translationSystem.getOldLanguageCode());
			query.executeUpdate();
			transaction.commit();
			logger.info(RECORD_UPDATED);
		} catch (HibernateException e) {
			logger.error(ERROR_IN_UPDATING_THE_RECORD + e.getMessage());
			transaction.rollback();
			throw e;
		} finally {
			logger.info(SESSION_CLOSED);
			session.close();
		}
		return AdminConstants.RECORD_ADDED;
	}

	/**
	 * Deletes the Languages where the given languages object matches.
	 *
	 * @param languages
	 *            the languages
	 *
	 * @return the string
	 *
	 * @throws HibernateException
	 *             the hibernate exception
	 */
	public static String delete(Languages languages) throws HibernateException {
		logger.info(CALLED_DELETE_METHOD);
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		try {
			session.delete(languages);
			transaction.commit();
			logger.info(RECORD_DELETED);
			return RECORD_DELETED;
		} catch (HibernateException e) {
			logger.error(ERROR_IN_DELETING_THE_RECORD);
			transaction.rollback();
			throw e;
		} finally {
			logger.info(SESSION_CLOSED);
			session.close();
		}
	}
}